package de.hska.test;

import static de.hska.util.LogUtil.begin;
import static de.hska.util.LogUtil.end;

import java.util.ArrayList;
import java.util.Collection;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import de.hska.kundenverwaltung.db.Kunde;

public class KundenverwaltungTestHelper extends Thread {
	private static final Log LOG = LogFactory.getLog(KundenverwaltungTestHelper.class);
	private static final boolean DEBUG = LOG.isDebugEnabled();
	
	private String cmd;
	private Long kundeId;
	private KundenverwaltungTestRemote kvProxy;
	
	/**
	 */
	public KundenverwaltungTestHelper(String cmd, Long kundeId) {
		if (DEBUG) begin(LOG, cmd, kundeId);
		this.cmd = cmd;
		this.kundeId = kundeId;
		if (DEBUG) end(LOG);
	}
	
	/**
	 */
	@Override
	public void run() {
		if (DEBUG) begin(LOG, cmd, kundeId);
		
		try {
			final Context ctx = new InitialContext();
			kvProxy = (KundenverwaltungTestRemote) ctx.lookup("testHska/KundenverwaltungTestBean/remote");
			ctx.close();
		}
		catch (NamingException e) {
			e.printStackTrace();
			return;
		}
		
		if ("update".equals(cmd)) {
			update();
		}
		else if ("delete".equals(cmd)) {
			delete();
		}
		else {
			System.err.println("Zulaessige Kommandos: \"update\" und \"delete\"");
		}
		
		if (DEBUG) end(LOG);
		return;
	}
	
	/**
	 */
	private void update() {
		if (DEBUG) begin(LOG);
		
		try {
			Kunde kunde = kvProxy.findKundeById(kundeId);
			
			kunde.setVorname(kunde.getVorname() + "concurrent");
			final Collection<Kunde> kunden = new ArrayList<Kunde>(1);
			kunden.add(kunde);
			
			kvProxy.updateKunden(kunden);
		}
		catch (Exception e) {
			if (DEBUG) end(LOG, e);
			throw new IllegalStateException(e);
		}
		
		if (DEBUG) end(LOG);
	}

	/**
	 */
	private void delete() {
		if (DEBUG) begin(LOG);
		
		try {
			kvProxy.deleteKundeById(kundeId);
		}
		catch (Exception e) {
			if (DEBUG) end(LOG, e);
			throw new IllegalStateException(e);
		}
		
		if (DEBUG) end(LOG);
	}
}
